from fastapi import APIRouter, Query, HTTPException
from pydantic import BaseModel
from typing import Optional
from service.FinalService import FinalService
from service.SessionService import SessionService

app = APIRouter(prefix="/ai", tags=["ai"])

# 初始化服务
session_service = SessionService()


class ChatRequest(BaseModel):
    session_id: str
    user_input: str

# 请求模型
class CreateSessionRequest(BaseModel):
    title: Optional[str] = None

class UpdateSessionRequest(BaseModel):
    title: str

class SearchRequest(BaseModel):
    keyword: str
    session_id: Optional[str] = None
    page: int = 1
    size: int = 20

# 获取所有会话列表
@app.get("/sessions")
async def get_all_sessions(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页大小")
):
    """获取所有会话列表"""
    result = session_service.get_all_sessions(page=page, size=size)
    return {
        "code": 200,
        "message": "获取成功",
        "data": result
    }

# 获取指定会话详情
@app.get("/sessions/{session_id}")
async def get_session_by_id(session_id: str):
    """获取指定会话详情"""
    session = session_service.get_session_by_id(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="会话不存在")
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": session
    }

# 创建新会话
@app.post("/sessions")
async def create_new_session():
    """创建新会话"""
    session = session_service.create_new_session()
    return {
        "code": 200,
        "message": "创建成功",
        "data": session
    }

# 更新会话标题
@app.put("/sessions/{session_id}")
async def update_session_title(session_id: str, request: UpdateSessionRequest):
    """更新会话标题"""
    success = session_service.update_session_title(session_id, request.title)
    if not success:
        raise HTTPException(status_code=404, detail="会话不存在")
    
    return {
        "code": 200,
        "message": "更新成功"
    }

# 删除会话
@app.delete("/sessions/{session_id}")
async def delete_session(session_id: str):
    """删除会话"""
    success = session_service.delete_session(session_id)
    if not success:
        raise HTTPException(status_code=404, detail="会话不存在")
    
    return {
        "code": 200,
        "message": "删除成功"
    }

# 获取会话对话历史
@app.get("/sessions/{session_id}/conversations")
async def get_conversation_history(
    session_id: str,
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(50, ge=1, le=100, description="每页大小")
):
    """获取指定会话的对话历史"""
    result = session_service.get_conversation_history(session_id, page=page, size=size)
    return {
        "code": 200,
        "message": "获取成功",
        "data": result
    }

# 搜索对话内容
@app.post("/search")
async def search_conversations(request: SearchRequest):
    """搜索对话内容"""
    result = session_service.search_conversations(
        keyword=request.keyword,
        session_id=request.session_id,
        page=request.page,
        size=request.size
    )
    return {
        "code": 200,
        "message": "搜索成功",
        "data": result
    }

# 获取会话统计信息
@app.get("/sessions/{session_id}/statistics")
async def get_session_statistics(session_id: str):
    """获取会话统计信息"""
    stats = session_service.get_session_statistics(session_id)
    if not stats:
        raise HTTPException(status_code=404, detail="会话不存在")
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": stats
    }



# 初始化FinalService
final_service = FinalService()

# AI对话接口
@app.post("/chat")
async def chat_with_ai(request: ChatRequest):
    """AI对话接口"""
    user_input = request.user_input
    session_id = request.session_id
    if not user_input:
        return {"code": 400, "message": "用户输入不能为空"}
    
    if not session_id:
        return {"code": 400, "message": "session_id不能为空"}
    
    result = final_service.process_user_input(user_input, session_id)
    
    if result.get("success"):
        return {
            "code": 200,
            "message": "对话成功",
            "data": {
                "response": result["response"],
                "usage": result.get("usage", {})
            }
        }
    else:
        return {
            "code": 500,
            "message": "对话失败",
            "error": result.get("error", "未知错误")
        }
    